const path = require('path')

const {
  fileuploadError,
  publishGoodsError,
  invalidGoodsError,
  updateGoodsError,
  invalidGoodsID,
  putawayGoodsError } = require('../constant/err.type')
const { createGoods, updataGoods, removeGoods, restoreGoods, findGoods } = require('../service/goods.service')
class GoodsController {
  async upload(ctx) {

    const { file } = ctx.request.files

    if (file) {
      ctx.body = {
        code: 0,
        message: '商品图片上传成功',
        result: {
          // path.basename(file.path) 
          goods_img: file.name
        }
      }
    } else {
      return ctx.app.emit('error', fileuploadError, ctx)
    }
    // ctx.body = file
  }
  async create(ctx) {
    try {
      const { updatedAt, createdAt, ...res } = await createGoods(ctx.request.body)
      ctx.body = {
        code: 0,
        message: '发布商品成功',
        result: res
      }
    } catch (err) {
      console.error('添加商品失败', err);
      return ctx.app.emit('error', publishGoodsError, ctx)
    }
  }
  async update(ctx) {
    try {
      const res = await updataGoods(ctx.params.id, ctx.request.body)
      if (res) {
        ctx.body = {
          code: 0,
          message: '修改成功',
          result: ''
        }
      } else {
        ctx.app.emit('error', invalidGoodsError, ctx)
      }
    } catch (err) {
      console.error('更新商品失败', err);
      ctx.app.emit('error', updateGoodsError, ctx)
    }

  }
  async remove(ctx) {
    try {
      const res = await removeGoods(ctx.params.id)
      // console.log(res);
      if (res) {
        ctx.body = {
          code: 0,
          message: '下架成功',
          result: ''
        }
      } else {
        ctx.app.emit('error', invalidGoodsID, ctx)
      }

    } catch (err) {
      ctx.app.emit('error', putawayGoodsError, ctx)
    }

  }
  async restore(ctx) {
    try {
      const res = await restoreGoods(ctx.params.id)
      // console.log(res);
      if (res) {
        ctx.body = {
          code: 0,
          message: '上架成功',
          result: ''
        }
      } else {
        ctx.app.emit('error', invalidGoodsID, ctx)
      }

    } catch (err) {
      ctx.app.emit('error', putawayGoodsError, ctx)
    }

  }
  async findAll(ctx) {
    const { pageNum = 1, pageSize = 5 } = ctx.request.query
    const res = await findGoods(pageNum, pageSize)
    ctx.body = {
      code: 0,
      message: '获取商品列表成功',
      result: res
    }
  }
}
module.exports = new GoodsController